package cn.mybatishelper.entity.java;

import cn.mybatishelper.entity.database.DatabaseEntity;
import cn.mybatishelper.entity.mybatis.ResultMapElement;
import cn.mybatishelper.exception.MybatisHelperException;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * 用于生成持久化类PO
 *
 * @author yao
 */
public class PersistenceEntity extends JavaEntity {
    private static final Logger LOGGER = LoggerFactory.getLogger(PersistenceEntity.class);

    public PersistenceEntity() {
        super();
    }

    public PersistenceEntity(String rootFilePath) {
        super(rootFilePath);
    }

    @Override
    public String toCodeString(DatabaseEntity databaseEntity) throws MybatisHelperException {
        if (!validateDatabaseEntity(databaseEntity)) {
            throw new MybatisHelperException("初始化持久化类时校验失败，数据库信息不全...");
        }
        LOGGER.info("开始转化表：" + databaseEntity.getTableName() + "的实体类内容...");

        String uid = System.currentTimeMillis() + new Random().nextInt(10000) + "3";
        StringBuilder str = new StringBuilder();
        str.append("package " + databaseEntity.getJavaPackageName() + ";\n");
        str.append("\n");
        str.append("import java.io.Serializable;\n");
        str.append("import java.util.Date;\n");
        str.append("\n");
        str.append("\n");
        str.append("public class " + databaseEntity.getObjectName() + " implements Serializable{\n");
        str.append("\tprivate static final long serialVersionUID = ");
        str.append(uid);
        str.append("L;\n");

        ResultMapElement element = new ResultMapElement();
        element.setDatabaseEntity(databaseEntity);
        String propertyStr = element.toCodeString();

        str.append(propertyStr);
        str.append("\n}");
        return str.toString();
    }

    @Override
    public void createFile(DatabaseEntity databaseEntity) throws MybatisHelperException {
        try {
            String content = this.toCodeString(databaseEntity);
            String packageUrl = databaseEntity.getJavaPackageName().replaceAll("\\.", "/");
            File file = new File(rootFilePath + File.separator + packageUrl + File.separator + databaseEntity.getObjectName() + ".java");
            FileUtils.writeStringToFile(file, content, "UTF-8");
        } catch (IOException e) {
            throw new MybatisHelperException("转化物理文件发生异常 : " + e.getMessage());
        }
    }
}
